//
//  ZLRefreshControl.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 17/1/3.
//  Copyright © 2017年 hanju001. All rights reserved.
//

import UIKit

//刷新状态切换的临界点
private let ZLRefreshOffset: CGFloat = 126

// Normal 普通状态什么也不做
/// Pulling 通过临界点，放手开始刷新
/// WillRefresh 用户超过临界点，并且放手
enum ZLRefreshState {
    case Normal
    case Pulling
    case WillRefresh
}

class ZLRefreshControl: UIControl {

    //刷新控件的父视图
    private var scrollView: UIScrollView?
    
    fileprivate lazy var refreshView: ZLRefreshView = ZLRefreshView.refreshView()
    
    init() {
        super.init(frame: CGRect())
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    /**
     newSuperview addSubVIEW方法会调用
     当添加到父视图的时候，newSuperView是父视图
     当父视图被移除的时候 newSuperview是nil
     */
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        //记录父视图
        guard let sv = newSuperview as? UIScrollView else{
            
            return
        }
        scrollView = sv
        //KVO监听contentoffset
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        
        guard let sv = scrollView else {
            
            return
        }
        //初始高度
        let height = -(sv.contentInset.top + sv.contentOffset.y)
        if height < 0 {
            
            return
        }
        //可以根据高度设置刷新控件的frame
        self.frame = CGRect(x: 0, y: -height, width: sv.bounds.width, height: height)
        //判断临界点
        print(height)
        // ---传递父视图高度 如果正在刷新就不传递
        if (refreshView.refreshSate != .WillRefresh){
            
            refreshView.parentViewHeight = height
        }
        
        
        if sv.isDragging {
            if height > ZLRefreshOffset && refreshView.refreshSate == .Normal{
                
                print("放手刷新")
                
                refreshView.refreshSate = .Pulling
            }else if height <= ZLRefreshOffset && refreshView.refreshSate == .Pulling{
             
                refreshView.refreshSate = .Normal
                print("再使劲。。。")
            }
        }else{
            
            //放手 -- 判断是否超过临界点
            if refreshView.refreshSate == .Pulling{
                //刷新结束之后需要将状态改为normal  才能继续响应刷新
                print("准备开始刷新")
                
                beginRefreshing()
                //发送刷新数据的事件
                sendActions(for: .valueChanged)
            }
            
            
        }
        
        
    }
    //本视图从父视图上移除
    override func removeFromSuperview() {
        
        //还存在
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        super.removeFromSuperview()
        //不存在
    }
    //开始刷新
    func beginRefreshing() {
        
        print("开始刷新")
        //判断父视图
        guard let sv = scrollView else {
            
            return
        }
        //如果正在刷新就返回
        if refreshView.refreshSate == .WillRefresh{
            
            return
        }
        //设置刷新视图的状态
        refreshView.refreshSate = .WillRefresh
        
        //设置刷新视图的父视图高度
        refreshView.parentViewHeight = ZLRefreshOffset
        
        //调整表格间距
        var inset = sv.contentInset
        inset.top += ZLRefreshOffset
        sv.contentInset = inset
    }
    
    //结束刷新
    func endRefreshing() {
        
        print("结束刷新")
        //判断父视图
        guard let sv = scrollView else {
            
            return
        }
        //判断是否正在刷新  如果不是就直接返回
        if refreshView.refreshSate != .WillRefresh{
            
            return
        }
        //设置刷新视图的状态
        refreshView.refreshSate = .Normal
        
        //调整表格间距
        var inset = sv.contentInset
        inset.top -= ZLRefreshOffset
        sv.contentInset = inset
    }
}

extension ZLRefreshControl {
    
    fileprivate func setupUI(){
        
        backgroundColor = super.backgroundColor
        
        //设置超纯边界不显示
        //clipsToBounds = true
        
        addSubview(refreshView)
        
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.width))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.height))
    }
}
